package com.duoduo.springboot.security.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.duoduo.springboot.security.dao.PermissionDao;
import com.duoduo.springboot.security.model.Permission;
import com.duoduo.springboot.security.vo.PermissionVO;
import com.duoduo.springboot.security.vo.RoleVO;

@Service
public class PermissionService {

	@Autowired
	private PermissionDao permissionDao;
	@Autowired
	private RoleService roleService;

	public List<PermissionVO> listPermissionsByRoleId(int roleId) {
		List<PermissionVO> result = new ArrayList<PermissionVO>(0);
		List<Permission> permissionList = permissionDao.listPermissionsByRoleId(roleId);
		if (!CollectionUtils.isEmpty(permissionList)) {
			for (Permission permission : permissionList) {
				result.add(PermissionVO.fromEntity(permission));
			}
		}
		return result;
	}

	public List<String> listPermissionNamesByRoleId(int roleId) {
		List<String> result = new ArrayList<String>(0);
		List<PermissionVO> permissions = listPermissionsByRoleId(roleId);
		if (!CollectionUtils.isEmpty(permissions)) {
			for (PermissionVO permission : permissions) {
				result.add(permission.getName());
			}
		}
		return result;
	}

	public List<PermissionVO> listPermissionsByUserId(int userId) {
		List<PermissionVO> result = new ArrayList<PermissionVO>(0);
		List<RoleVO> roles = roleService.listRolesByUserId(userId);
		if (!CollectionUtils.isEmpty(roles)) {
			for (RoleVO role : roles) {
				List<PermissionVO> voList = listPermissionsByRoleId(role.getId());
				if (CollectionUtils.isEmpty(voList)) {
					continue;
				}

				for (PermissionVO vo : voList) {
					if (!result.contains(vo)) {
						result.add(vo);
					}
				}
			}
		}
		return result;
	}
}
